using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using OA.Common.Img;
using System.Drawing.Imaging;

namespace OA.Mvc3.Controllers
{
    [ValidateInput(false)]
    public class ToolsController : UI.BaseController
    {

        #region 验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="key"></param>
        public void VerifyCode(string key)
        {
            if (string.IsNullOrEmpty(key) || key.Trim() == "") return;
            key = key.Trim();

            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
            Response.ContentType = "image/png";

            MemoryStream ms = new MemoryStream();
            YZMHelper yzm = new YZMHelper(2, 4);
            Session[key] = yzm.Text;
            try
            {
                yzm.Image.Save(ms, ImageFormat.Png);
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                ms.Dispose();
                yzm.Image.Dispose();
            }
        }
        #endregion

        #region 数据选择对话框
        /// <summary>
        /// 获取对话框
        /// </summary>
        /// <param name="dialogCode">对话框编号</param>
        /// <param name="multiSelected">是否多选</param>
        /// <param name="firstShow">是否直接显示查询结果</param>
        /// <returns></returns>
        [UI.LoginValidate]
        public ViewResult Dialog(string dialogCode,bool? multiSelected,bool? firstShow,string where)
        {
            ViewBag.multiSelected = multiSelected;
            ViewBag.firstShow = firstShow;
            ViewBag.where = where;
            if(!string.IsNullOrEmpty(ViewBag.where)) ViewBag.where=ViewBag.where.Replace("'","\\'");

            Model.Dialog dialog = new BLL.Dialog().Get(dialogCode);
            dialog.Fields=dialog.Fields.OrderByDescending(r => r.Sort).ToList();
            return View(dialog);
        }

        [UI.LoginValidate]
        public string DialogData(string dialogCode, string where, int page, int rows, string sort, string order)
        {
            var bll= new BLL.Dialog();
            var dialog = bll.Get(dialogCode);
            if (dialog == null) return null;
            var fileds = dialog.Fields.Where(r => r.IsShow == true);
            string whereByKey = "";
            foreach (var f in fileds)
            {
                whereByKey += f.FieldKey + ",";
            }
            if (whereByKey.Length > 0) whereByKey = whereByKey.Substring(0, whereByKey.Length - 1);
            var type = bll.DialogData(dialogCode,null, null, 0, 1);
            if (type.Count == 0) return null;

            string wherestr = Common.HqlQeuryHelp.GetWhere(type[0].GetType(), whereByKey);
            if (string.IsNullOrEmpty(wherestr)) wherestr = "1=1";
            if (!string.IsNullOrEmpty(where))
            {
                wherestr+=" and " + where;
            }
            string orderby = null;
            if (!string.IsNullOrEmpty(sort)) orderby = sort + " " + order;

            var data = bll.DialogData(dialogCode, wherestr, orderby, (page - 1) * rows, rows);
            List<object> listView=new List<object>();
            foreach (var i in data)
            {
                dynamic model = new ViewDataDictionary(); 
                foreach (var field in fileds)
                {
                    var value = i.GetType().GetProperty(field.FieldKey).GetValue(i, null);
                    model[field.FieldKey] = value;
                }
                listView.Add(model);
            }
            var ret = new
            {
                total = bll.DialogDataCount(dialogCode,wherestr),
                rows = listView
            };
            return UI.Utils.ToJsonString(ret);
        }

        #endregion

        #region 文件上传

        [UI.LoginValidate]
        public string UpLoadFile(string uploadControlName, bool? isImage, bool isThumbnai,bool?isWatermark,string customSavePath)
        {
            var file = Request.Files[uploadControlName];
            var upload = new UI.UploadFile();
            var config=BLL.SystemConfig.LoadConfig().Upload;

            if (!string.IsNullOrEmpty(customSavePath))
            {
                config.AttachSave = 0;
                config.AttachPath = customSavePath;
            }
            var ret = upload.Save(file, config, isImage, isThumbnai, isWatermark);
            return UI.Utils.ToJsonString(ret);
        }

        [UI.LoginValidate]
        public string UploadIcon(string uploadControlName)
        {
            var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<Common.Result>(UpLoadFile(uploadControlName, true, false, false, "~/Content/Images/UploadIcons"));
            string filePath = ret.data.ToString();
            string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
            string dirPath=System.IO.Path.GetDirectoryName(filePath);
            string[] css = { ".icon" + fileName + " {background:url(" + System.IO.Path.GetFileName(filePath) + ") no-repeat}" };
            System.IO.File.AppendAllLines(Server.MapPath(dirPath + "/icons.css"), css);
            ret.data = "icon" + fileName;
            return UI.Utils.ToJsonString(ret);
        }

        [UI.LoginValidate]
        public string KeUpload(string dir, HttpPostedFileBase imgFile,bool?isWatermark, string savePath,string localUrl)
        {
            var config = BLL.SystemConfig.LoadConfig().Upload;
            if (!string.IsNullOrEmpty(savePath))
            {
                config.AttachPath = savePath;
            }
            var upload = new UI.UploadFile();
            var result = upload.Save(imgFile, config, dir == "image", false, isWatermark);
            if (result.success)
            {
                var ret = new
                {
                    error = 0,
                    url = result.data.ToString()
                };
                return UI.Utils.ToJsonString(ret);
            }
            else
            {
                var ret = new
                {
                    error = 1,
                    message = result.message
                };
                return UI.Utils.ToJsonString(ret);
            }

        }

        #endregion

        #region 单点登陆

        /// <summary>
        /// 获取登陆凭证
        /// </summary>
        [UI.LoginValidate]
        public ActionResult GetToken(string BackUrl)
        {
            return Redirect(UI.Utils.GetUrlParames(BackUrl, "Token", Session.SessionID));
        }

        /// <summary>
        /// 获取当前登陆用户信息
        /// </summary>
        public string GetLoginUserByToken(string Token)
        {
            string xml = "";
            var loginguser = BLL.LoginUser.OnLineManagers.FirstOrDefault(r => r.IsKick == false && r.SessionID == Token);
            if (loginguser != null)
            {
                var user= new BLL.Manager().Get(loginguser.UserName);
                var ret = new Service.Model.Data.User()
                {
                    UserName = user.UserName,
                    Password = user.Password,
                    RealName = user.RealName,
                    GroupID = user.GroupID,
                    Email = user.Email,
                    Telephone = user.Telephone,
                    CreatTime = user.CreatTime
                };
                xml = Common.SerializationHelper.Serialize(ret);
            }
            return xml;
        }
        #endregion
    }
}
